﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Collections;

namespace iPdf
{
    class AsyncIdleQueue
    {
        private AsyncIdleQueue() { }

        private class QueuedDetails
        {
            #region Fields
            private IAsyncResult _result;
            private AsyncCallback _callback;
            #endregion
            public QueuedDetails(IAsyncResult result, AsyncCallback callback)
            {
                _result = result;
                _callback = callback;
            }

            public bool InvokeIfComplete()
            {
                bool done = _result.IsCompleted;
                if (done && _callback != null)
                {
                    _callback(_result);
                }

                return done;
            }
        }

        static AsyncIdleQueue()
        {
            Application.Idle += new EventHandler(OnApplicationIdle);
        }

        public static void AddEntry(IAsyncResult result, AsyncCallback callback)
        {
            Entries.Add(new QueuedDetails(result, callback));
        }

        private static void OnApplicationIdle(object sender, EventArgs e)
        {
            for (int i = 0; i < Entries.Count; ++i)
            {
                QueuedDetails d = (QueuedDetails)Entries[i];

                if (d.InvokeIfComplete())
                {
                    Entries.Remove(d);
                    --i;
                }

            }
        }

        private static ArrayList Entries
        {
            get
            {
                if (_entries == null)
                {
                    _entries = new ArrayList();
                }

                return _entries;
            }

        }

        private static ArrayList _entries;

    }
}
